package com.sunsy.authserver.service.role;

import com.sunsy.authserver.beans.dto.AccessTokenDTO;
import com.sunsy.authserver.beans.dto.LoginDto;
import com.sunsy.authserver.beans.po.AppClient;
import com.sunsy.authserver.dao.AppClientDao;
import com.sunsy.authserver.enums.ErrorCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Repository;

/**
 * @author sunsiyuan
 * 检查应用参数是否合规
 */
@Aspect
@Order(1)
@Repository
public class ClientRole {

    private AppClientDao appClientDao;

    @Autowired
    public void setAppClientDao(AppClientDao appClientDao) {
        this.appClientDao = appClientDao;
    }


    @Around("execution(* com.sunsy.authserver.service.AccessTokenService.createToken(..)) ||" +
            "execution(* com.sunsy.authserver.service.AccessTokenService.refreshToken(..));")
    public Object checkClient(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        AccessTokenDTO dto = (AccessTokenDTO) proceedingJoinPoint.getArgs()[0];
        checkClient(dto.getClientId(), dto.getClientSecret());
        return proceedingJoinPoint.proceed();
    }

    @Around("execution(* com.sunsy.authserver.service.LoginService.generalLogin(..))")
    public Object check(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        LoginDto dto = (LoginDto) proceedingJoinPoint.getArgs()[0];
        AppClient client = checkClient(dto.getClientId(), dto.getClientSecret());
        if (!client.getRedirectUrl().equals(dto.getCallback_url())) {
            ErrorCode.APP_CLIENT_CALLBACK_EXC.apiExc();
        }
        return proceedingJoinPoint.proceed();
    }

    private AppClient checkClient(String clientId, String clientSecret) {
        //      校验clientID和clientsecret 对得上不
        AppClient client = appClientDao.getApp(clientId);
        if (client == null) {
            ErrorCode.APP_CLIENT_NOT_FOUNT.apiExc();
        }
        if (!client.getAppSecret().equals(clientSecret)) {
            ErrorCode.APP_SECRET_EXC.apiExc();
        }
        return client;
    }

}
